package com.pai4j.zwiki.service.agent;

import com.pai4j.zwiki.domain.entity.CodeStructureEntity;
import com.pai4j.zwiki.repository.CodeStructureRepository;
import com.pai4j.zwiki.service.LLMService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 代码洞察分析器
 * 
 * 提供深层次的代码理解和洞察，超越表面的代码阅读
 * 
 * 核心能力：
 * 1. 架构模式识别 - 识别和理解代码中的架构模式
 * 2. 设计意图推断 - 推断代码背后的设计意图和思想
 * 3. 代码演化分析 - 分析代码的演化历史和重构痕迹
 * 4. 隐含知识提取 - 提取代码中的隐含知识和最佳实践
 * 5. 技术债务识别 - 识别技术债务和潜在问题
 * 6. 重构建议生成 - 生成具体可行的重构建议
 *
 * @author pai4j
 * @since 2025-10-12
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CodeInsightAnalyzer {

    private final LLMService llmService;
    private final CodeStructureRepository codeStructureRepository;
    private final EnhancedPromptEngine promptEngine;

    /**
     * 执行全面的代码洞察分析（优化版 - 支持上下文传递）
     * 
     * @param taskId 任务ID
     * @param workspacePath 工作空间路径
     * @param deepReadingReport 深度阅读报告（上下文）
     * @param previousAnalysis 之前的分析结果（上下文）
     * @return 洞察分析结果
     */
    public Map<String, Object> analyzeCodeInsightsWithContext(String taskId, String workspacePath, 
                                                               Map<String, Object> deepReadingReport,
                                                               Map<String, Object> previousAnalysis) {
        log.info("开始执行代码洞察分析（带上下文）, 任务ID: {}", taskId);
        
        // 构建上下文摘要
        String contextSummary = buildContextSummary(deepReadingReport, previousAnalysis);
        log.info("已构建上下文摘要，长度: {} 字符", contextSummary.length());
        
        return analyzeCodeInsightsInternal(taskId, workspacePath, contextSummary);
    }

    /**
     * 执行全面的代码洞察分析（向后兼容）
     */
    public Map<String, Object> analyzeCodeInsights(String taskId, String workspacePath) {
        log.info("开始执行代码洞察分析, 任务ID: {}", taskId);
        return analyzeCodeInsightsInternal(taskId, workspacePath, null);
    }
    
    /**
     * 内部洞察分析方法
     */
    private Map<String, Object> analyzeCodeInsightsInternal(String taskId, String workspacePath, String contextSummary) {

        Map<String, Object> insights = new HashMap<>();

        try {
            Path projectPath = Paths.get(workspacePath);
            List<CodeStructureEntity> structures = codeStructureRepository.findByTaskId(taskId);

            // 1. 架构模式深度识别
            log.info("1. 识别架构模式");
            Map<String, Object> architecturePatterns = identifyArchitecturePatterns(structures, projectPath, contextSummary);
            insights.put("architecturePatterns", architecturePatterns);

            // 2. 设计原则遵循度分析
            log.info("2. 分析设计原则遵循度");
            Map<String, Object> designPrinciples = analyzeDesignPrinciples(structures, projectPath);
            insights.put("designPrinciples", designPrinciples);

            // 3. 代码复杂度深度分析
            log.info("3. 分析代码复杂度");
            Map<String, Object> complexityAnalysis = analyzeComplexity(structures, projectPath);
            insights.put("complexityAnalysis", complexityAnalysis);

            // 4. 安全漏洞扫描
            log.info("4. 扫描安全漏洞");
            List<Map<String, Object>> securityIssues = scanSecurityVulnerabilities(structures, projectPath);
            insights.put("securityIssues", securityIssues);

            // 5. 性能瓶颈识别
            log.info("5. 识别性能瓶颈");
            List<Map<String, Object>> performanceBottlenecks = identifyPerformanceBottlenecks(structures, projectPath);
            insights.put("performanceBottlenecks", performanceBottlenecks);

            // 6. 技术债务评估
            log.info("6. 评估技术债务");
            Map<String, Object> technicalDebt = assessTechnicalDebt(structures, projectPath);
            insights.put("technicalDebt", technicalDebt);

            // 7. 重构机会识别
            log.info("7. 识别重构机会");
            List<Map<String, Object>> refactoringOpportunities = identifyRefactoringOpportunities(structures, projectPath);
            insights.put("refactoringOpportunities", refactoringOpportunities);

            // 8. 最佳实践提取
            log.info("8. 提取最佳实践");
            List<Map<String, Object>> bestPractices = extractBestPractices(structures, projectPath);
            insights.put("bestPractices", bestPractices);

            // 9. 生成改进路线图
            log.info("9. 生成改进路线图");
            String improvementRoadmap = generateImprovementRoadmap(insights);
            insights.put("improvementRoadmap", improvementRoadmap);

            log.info("代码洞察分析完成");

        } catch (Exception e) {
            log.error("代码洞察分析失败", e);
            insights.put("error", e.getMessage());
        }

        return insights;
    }

    /**
     * 1. 架构模式深度识别
     */
    private Map<String, Object> identifyArchitecturePatterns(List<CodeStructureEntity> structures, Path projectPath, String contextSummary) {
        Map<String, Object> patterns = new HashMap<>();

        try {
            // 分析包结构
            Map<String, List<CodeStructureEntity>> packageGroups = structures.stream()
                    .filter(s -> s.getPackageName() != null)
                    .collect(Collectors.groupingBy(CodeStructureEntity::getPackageName));

            // 构建项目结构摘要
            Map<String, Object> structureSummary = new HashMap<>();
            structureSummary.put("totalPackages", packageGroups.size());
            structureSummary.put("totalClasses", structures.size());
            structureSummary.put("packageDistribution", packageGroups.entrySet().stream()
                    .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().size())));

            // 识别分层结构
            Map<String, List<String>> layerIdentification = identifyLayers(packageGroups);
            patterns.put("layers", layerIdentification);

            // 识别模块划分
            Map<String, List<String>> moduleIdentification = identifyModules(packageGroups);
            patterns.put("modules", moduleIdentification);

            // 使用LLM进行深度架构分析（传递上下文）
            String dependencyInfo = buildDependencyGraph(structures);
            String architecturePrompt;
            
            if (contextSummary != null && !contextSummary.isEmpty()) {
                // 带上下文的架构分析
                architecturePrompt = buildArchitecturePromptWithContext(
                    structureSummary, dependencyInfo, contextSummary
                );
            } else {
                // 原有的架构分析
                architecturePrompt = promptEngine.buildArchitectureAnalysisPrompt(
                    structureSummary, dependencyInfo
                );
            }
            
            String llmArchitectureAnalysis = llmService.generateCodeSummary(architecturePrompt);
            patterns.put("llmArchitectureAnalysis", llmArchitectureAnalysis);

            // 识别架构风格
            String architectureStyle = identifyArchitectureStyle(packageGroups, llmArchitectureAnalysis);
            patterns.put("architectureStyle", architectureStyle);

        } catch (Exception e) {
            log.error("架构模式识别失败", e);
            patterns.put("error", e.getMessage());
        }

        return patterns;
    }

    /**
     * 2. 设计原则遵循度分析
     */
    private Map<String, Object> analyzeDesignPrinciples(List<CodeStructureEntity> structures, Path projectPath) {
        Map<String, Object> principles = new HashMap<>();

        try {
            // 选择代表性的类进行分析 - 增加分析数量以获得更全面的理解
            List<CodeStructureEntity> representativeClasses = selectRepresentativeClasses(structures, 20);

            List<Map<String, Object>> classAnalyses = new ArrayList<>();

            for (CodeStructureEntity structure : representativeClasses) {
                try {
                    Path filePath = Paths.get(structure.getFilePath());
                    if (!Files.exists(filePath)) continue;

                    String code = Files.readString(filePath);
                    if (code.isEmpty()) continue;

                    // 计算基本度量
                    Map<String, Object> metrics = calculateCodeMetrics(code, structure);

                    // 使用LLM进行质量评估
                    String qualityPrompt = promptEngine.buildCodeQualityAssessmentPrompt(
                            code,
                            structure.getFilePath(),
                            metrics
                    );
                    String qualityAnalysis = llmService.generateCodeSummary(qualityPrompt);

                    Map<String, Object> classAnalysis = new HashMap<>();
                    classAnalysis.put("className", structure.getName());
                    classAnalysis.put("filePath", structure.getFilePath());
                    classAnalysis.put("metrics", metrics);
                    classAnalysis.put("qualityAnalysis", qualityAnalysis);

                    classAnalyses.add(classAnalysis);

                } catch (Exception e) {
                    log.warn("分析类 {} 失败: {}", structure.getName(), e.getMessage());
                }
            }

            principles.put("classAnalyses", classAnalyses);

            // 生成总体设计原则遵循度报告
            if (!classAnalyses.isEmpty()) {
                String summaryPrompt = buildDesignPrinciplesSummaryPrompt(classAnalyses);
                String overallAssessment = llmService.generateCodeSummary(summaryPrompt);
                principles.put("overallAssessment", overallAssessment);
            }

        } catch (Exception e) {
            log.error("设计原则分析失败", e);
            principles.put("error", e.getMessage());
        }

        return principles;
    }

    /**
     * 3. 代码复杂度深度分析
     */
    private Map<String, Object> analyzeComplexity(List<CodeStructureEntity> structures, Path projectPath) {
        Map<String, Object> complexity = new HashMap<>();

        try {
            // 统计复杂度指标
            List<Map<String, Object>> complexClasses = new ArrayList<>();

            for (CodeStructureEntity structure : structures) {
                try {
                    Path filePath = Paths.get(structure.getFilePath());
                    if (!Files.exists(filePath)) continue;

                    String code = Files.readString(filePath);
                    if (code.isEmpty()) continue;

                    // 计算复杂度指标
                    int methodCount = countMethods(code);
                    int lineCount = structure.getLineCount() != null ? structure.getLineCount() : 0;
                    int dependencyCount = countDependencies(code);

                    // 识别复杂类（方法多、行数多、依赖多）
                    if (methodCount > 15 || lineCount > 500 || dependencyCount > 10) {
                        Map<String, Object> complexClass = new HashMap<>();
                        complexClass.put("className", structure.getName());
                        complexClass.put("filePath", structure.getFilePath());
                        complexClass.put("methodCount", methodCount);
                        complexClass.put("lineCount", lineCount);
                        complexClass.put("dependencyCount", dependencyCount);
                        complexClass.put("complexityScore", calculateComplexityScore(methodCount, lineCount, dependencyCount));

                        complexClasses.add(complexClass);
                    }

                } catch (Exception e) {
                    log.warn("分析类 {} 的复杂度失败: {}", structure.getName(), e.getMessage());
                }
            }

            // 按复杂度排序
            complexClasses.sort((a, b) -> 
                    Integer.compare((Integer) b.get("complexityScore"), (Integer) a.get("complexityScore")));

            complexity.put("complexClasses", complexClasses.stream().limit(15).collect(Collectors.toList()));

            // 对最复杂的类进行深度分析
            if (!complexClasses.isEmpty()) {
                Map<String, Object> mostComplexClass = complexClasses.get(0);
                String filePath = (String) mostComplexClass.get("filePath");
                String code = Files.readString(Paths.get(filePath));

                String complexityPrompt = buildComplexityAnalysisPrompt(
                        mostComplexClass.get("className").toString(),
                        code,
                        mostComplexClass
                );
                String deepComplexityAnalysis = llmService.generateCodeSummary(complexityPrompt);
                complexity.put("deepComplexityAnalysis", deepComplexityAnalysis);
            }

            // 计算整体复杂度指标
            double avgMethodsPerClass = structures.stream()
                    .mapToInt(s -> {
                        try {
                            return countMethods(Files.readString(Paths.get(s.getFilePath())));
                        } catch (Exception e) {
                            return 0;
                        }
                    })
                    .average()
                    .orElse(0.0);

            complexity.put("averageMethodsPerClass", Math.round(avgMethodsPerClass * 10.0) / 10.0);
            complexity.put("totalComplexClasses", complexClasses.size());

        } catch (Exception e) {
            log.error("复杂度分析失败", e);
            complexity.put("error", e.getMessage());
        }

        return complexity;
    }

    /**
     * 4. 安全漏洞扫描
     */
    private List<Map<String, Object>> scanSecurityVulnerabilities(List<CodeStructureEntity> structures, Path projectPath) {
        List<Map<String, Object>> issues = new ArrayList<>();

        try {
            // 识别安全关键类（Controller、Service等）- 增加分析数量
            List<CodeStructureEntity> securityCriticalClasses = structures.stream()
                    .filter(s -> s.getName().endsWith("Controller") ||
                               s.getName().endsWith("Service") ||
                               s.getName().contains("Auth") ||
                               s.getName().contains("Security"))
                    .limit(20) // 增加安全审查的范围
                    .collect(Collectors.toList());

            for (CodeStructureEntity structure : securityCriticalClasses) {
                try {
                    Path filePath = Paths.get(structure.getFilePath());
                    if (!Files.exists(filePath)) continue;

                    String code = Files.readString(filePath);
                    if (code.isEmpty()) continue;

                    // 使用LLM进行安全分析
                    String securityPrompt = promptEngine.buildSecurityAnalysisPrompt(
                            code,
                            structure.getFilePath(),
                            structure.getStructureType()
                    );
                    String securityAnalysis = llmService.generateCodeSummary(securityPrompt);

                    // 快速扫描常见安全问题
                    List<String> quickScanIssues = quickSecurityScan(code);

                    Map<String, Object> securityReport = new HashMap<>();
                    securityReport.put("className", structure.getName());
                    securityReport.put("filePath", structure.getFilePath());
                    securityReport.put("llmAnalysis", securityAnalysis);
                    securityReport.put("quickScanIssues", quickScanIssues);

                    issues.add(securityReport);

                } catch (Exception e) {
                    log.warn("安全扫描类 {} 失败: {}", structure.getName(), e.getMessage());
                }
            }

        } catch (Exception e) {
            log.error("安全漏洞扫描失败", e);
        }

        return issues;
    }

    /**
     * 5. 性能瓶颈识别
     */
    private List<Map<String, Object>> identifyPerformanceBottlenecks(List<CodeStructureEntity> structures, Path projectPath) {
        List<Map<String, Object>> bottlenecks = new ArrayList<>();

        try {
            // 识别可能有性能问题的类 - 增加分析范围
            List<CodeStructureEntity> performanceCriticalClasses = structures.stream()
                    .filter(s -> s.getName().endsWith("Service") ||
                               s.getName().endsWith("Repository") ||
                               s.getName().endsWith("Dao") ||
                               s.getName().contains("Batch") ||
                               s.getName().contains("Task"))
                    .limit(15) // 增加性能分析的范围
                    .collect(Collectors.toList());

            for (CodeStructureEntity structure : performanceCriticalClasses) {
                try {
                    Path filePath = Paths.get(structure.getFilePath());
                    if (!Files.exists(filePath)) continue;

                    String code = Files.readString(filePath);
                    if (code.isEmpty()) continue;

                    // 快速识别性能问题特征
                    List<String> performanceIssues = quickPerformanceScan(code);

                    if (!performanceIssues.isEmpty()) {
                        // 使用LLM进行深度性能分析
                        String performancePrompt = promptEngine.buildPerformanceAnalysisPrompt(
                                code,
                                structure.getFilePath(),
                                "这个类可能存在性能问题: " + String.join(", ", performanceIssues)
                        );
                        String performanceAnalysis = llmService.generateCodeSummary(performancePrompt);

                        Map<String, Object> performanceReport = new HashMap<>();
                        performanceReport.put("className", structure.getName());
                        performanceReport.put("filePath", structure.getFilePath());
                        performanceReport.put("quickScanIssues", performanceIssues);
                        performanceReport.put("llmAnalysis", performanceAnalysis);

                        bottlenecks.add(performanceReport);
                    }

                } catch (Exception e) {
                    log.warn("性能分析类 {} 失败: {}", structure.getName(), e.getMessage());
                }
            }

        } catch (Exception e) {
            log.error("性能瓶颈识别失败", e);
        }

        return bottlenecks;
    }

    /**
     * 6. 技术债务评估
     */
    private Map<String, Object> assessTechnicalDebt(List<CodeStructureEntity> structures, Path projectPath) {
        Map<String, Object> debt = new HashMap<>();

        try {
            List<Map<String, Object>> debtItems = new ArrayList<>();

            // 1. 识别大类（技术债务的常见来源）
            List<CodeStructureEntity> largeClasses = structures.stream()
                    .filter(s -> s.getLineCount() != null && s.getLineCount() > 500)
                    .sorted((a, b) -> Integer.compare(b.getLineCount(), a.getLineCount()))
                    .limit(10)
                    .collect(Collectors.toList());

            for (CodeStructureEntity largeClass : largeClasses) {
                Map<String, Object> debtItem = new HashMap<>();
                debtItem.put("type", "大类（上帝类）");
                debtItem.put("className", largeClass.getName());
                debtItem.put("filePath", largeClass.getFilePath());
                debtItem.put("lineCount", largeClass.getLineCount());
                debtItem.put("severity", "高");
                debtItem.put("description", "类过大，可能承担了过多职责，违反单一职责原则");
                debtItems.add(debtItem);
            }

            // 2. 识别重复代码（基于类名模式）
            Map<String, Long> classNamePatterns = structures.stream()
                    .map(s -> extractClassNamePattern(s.getName()))
                    .collect(Collectors.groupingBy(p -> p, Collectors.counting()));

            classNamePatterns.entrySet().stream()
                    .filter(e -> e.getValue() > 5)
                    .forEach(e -> {
                        Map<String, Object> debtItem = new HashMap<>();
                        debtItem.put("type", "可能的重复代码");
                        debtItem.put("pattern", e.getKey());
                        debtItem.put("count", e.getValue());
                        debtItem.put("severity", "中");
                        debtItem.put("description", "发现多个类似命名的类，可能存在代码重复");
                        debtItems.add(debtItem);
                    });

            // 3. 识别过时的API使用（需要读取代码）
            for (CodeStructureEntity structure : structures.stream().limit(20).collect(Collectors.toList())) {
                try {
                    Path filePath = Paths.get(structure.getFilePath());
                    if (!Files.exists(filePath)) continue;

                    String code = Files.readString(filePath);
                    List<String> deprecatedUsages = findDeprecatedUsages(code);

                    if (!deprecatedUsages.isEmpty()) {
                        Map<String, Object> debtItem = new HashMap<>();
                        debtItem.put("type", "使用过时API");
                        debtItem.put("className", structure.getName());
                        debtItem.put("filePath", structure.getFilePath());
                        debtItem.put("deprecatedApis", deprecatedUsages);
                        debtItem.put("severity", "中");
                        debtItem.put("description", "使用了@Deprecated标记的API");
                        debtItems.add(debtItem);
                    }
                } catch (Exception e) {
                    // 忽略
                }
            }

            debt.put("debtItems", debtItems);
            debt.put("totalDebtItems", debtItems.size());

            // 计算技术债务评分
            int debtScore = calculateTechnicalDebtScore(debtItems);
            debt.put("debtScore", debtScore);
            debt.put("debtLevel", getDebtLevel(debtScore));

        } catch (Exception e) {
            log.error("技术债务评估失败", e);
            debt.put("error", e.getMessage());
        }

        return debt;
    }

    /**
     * 7. 重构机会识别
     */
    private List<Map<String, Object>> identifyRefactoringOpportunities(List<CodeStructureEntity> structures, Path projectPath) {
        List<Map<String, Object>> opportunities = new ArrayList<>();

        try {
            // 识别长方法
            for (CodeStructureEntity structure : structures.stream().limit(30).collect(Collectors.toList())) {
                try {
                    Path filePath = Paths.get(structure.getFilePath());
                    if (!Files.exists(filePath)) continue;

                    String code = Files.readString(filePath);
                    List<String> longMethods = findLongMethods(code);

                    if (!longMethods.isEmpty()) {
                        Map<String, Object> opportunity = new HashMap<>();
                        opportunity.put("type", "提取方法");
                        opportunity.put("className", structure.getName());
                        opportunity.put("filePath", structure.getFilePath());
                        opportunity.put("longMethods", longMethods);
                        opportunity.put("recommendation", "将长方法拆分为多个小方法，提高可读性和可测试性");
                        opportunities.add(opportunity);
                    }

                    // 识别重复代码块
                    if (code.contains("// TODO") || code.contains("// FIXME")) {
                        Map<String, Object> opportunity = new HashMap<>();
                        opportunity.put("type", "完成待办事项");
                        opportunity.put("className", structure.getName());
                        opportunity.put("filePath", structure.getFilePath());
                        opportunity.put("recommendation", "完成代码中的TODO和FIXME标记");
                        opportunities.add(opportunity);
                    }

                } catch (Exception e) {
                    // 忽略
                }
            }

        } catch (Exception e) {
            log.error("重构机会识别失败", e);
        }

        return opportunities;
    }

    /**
     * 8. 最佳实践提取
     */
    private List<Map<String, Object>> extractBestPractices(List<CodeStructureEntity> structures, Path projectPath) {
        List<Map<String, Object>> practices = new ArrayList<>();

        try {
            // 识别高质量的代码
            for (CodeStructureEntity structure : structures) {
                try {
                    Path filePath = Paths.get(structure.getFilePath());
                    if (!Files.exists(filePath)) continue;

                    String code = Files.readString(filePath);
                    if (code.isEmpty()) continue;

                    // 识别好的实践
                    List<String> goodPractices = identifyGoodPractices(code, structure);

                    if (!goodPractices.isEmpty()) {
                        Map<String, Object> practice = new HashMap<>();
                        practice.put("className", structure.getName());
                        practice.put("filePath", structure.getFilePath());
                        practice.put("practices", goodPractices);
                        practices.add(practice);
                    }

                } catch (Exception e) {
                    // 忽略
                }

                if (practices.size() >= 10) break;
            }

        } catch (Exception e) {
            log.error("最佳实践提取失败", e);
        }

        return practices;
    }

    /**
     * 9. 生成改进路线图
     */
    private String generateImprovementRoadmap(Map<String, Object> insights) {
        StringBuilder roadmap = new StringBuilder();

        roadmap.append("# 项目改进路线图\n\n");

        // 基于分析结果生成路线图
        roadmap.append("## 短期改进（1-2周）\n\n");
        
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> securityIssues = (List<Map<String, Object>>) insights.get("securityIssues");
        if (securityIssues != null && !securityIssues.isEmpty()) {
            roadmap.append("### 1. 修复安全问题（优先级：高）\n");
            roadmap.append("发现 ").append(securityIssues.size()).append(" 个需要安全审查的类\n");
            roadmap.append("- 修复输入验证问题\n");
            roadmap.append("- 加强认证和授权\n");
            roadmap.append("- 处理敏感数据加密\n\n");
        }

        roadmap.append("## 中期改进（1-2个月）\n\n");

        @SuppressWarnings("unchecked")
        List<Map<String, Object>> performanceBottlenecks = (List<Map<String, Object>>) insights.get("performanceBottlenecks");
        if (performanceBottlenecks != null && !performanceBottlenecks.isEmpty()) {
            roadmap.append("### 2. 性能优化（优先级：中）\n");
            roadmap.append("发现 ").append(performanceBottlenecks.size()).append(" 个潜在性能瓶颈\n");
            roadmap.append("- 优化数据库查询\n");
            roadmap.append("- 添加缓存机制\n");
            roadmap.append("- 优化算法复杂度\n\n");
        }

        @SuppressWarnings("unchecked")
        List<Map<String, Object>> refactoringOpportunities = (List<Map<String, Object>>) insights.get("refactoringOpportunities");
        if (refactoringOpportunities != null && !refactoringOpportunities.isEmpty()) {
            roadmap.append("### 3. 代码重构（优先级：中）\n");
            roadmap.append("发现 ").append(refactoringOpportunities.size()).append(" 个重构机会\n");
            roadmap.append("- 提取长方法\n");
            roadmap.append("- 消除代码重复\n");
            roadmap.append("- 简化复杂逻辑\n\n");
        }

        roadmap.append("## 长期改进（3-6个月）\n\n");

        @SuppressWarnings("unchecked")
        Map<String, Object> technicalDebt = (Map<String, Object>) insights.get("technicalDebt");
        if (technicalDebt != null) {
            roadmap.append("### 4. 偿还技术债务（优先级：中）\n");
            roadmap.append("- 拆分大类\n");
            roadmap.append("- 改进模块划分\n");
            roadmap.append("- 升级过时依赖\n\n");
        }

        roadmap.append("### 5. 架构演进（优先级：低）\n");
        roadmap.append("- 优化分层结构\n");
        roadmap.append("- 提升模块内聚性\n");
        roadmap.append("- 减少模块耦合\n\n");

        roadmap.append("---\n\n");
        roadmap.append("**注意**: 以上路线图基于自动化分析生成，具体实施需要根据团队实际情况调整。\n");

        return roadmap.toString();
    }

    // ========== 辅助方法 ==========

    private Map<String, List<String>> identifyLayers(Map<String, List<CodeStructureEntity>> packageGroups) {
        Map<String, List<String>> layers = new HashMap<>();
        
        List<String> controllerLayer = new ArrayList<>();
        List<String> serviceLayer = new ArrayList<>();
        List<String> repositoryLayer = new ArrayList<>();
        List<String> domainLayer = new ArrayList<>();
        List<String> configLayer = new ArrayList<>();
        List<String> otherLayers = new ArrayList<>();

        packageGroups.keySet().forEach(pkg -> {
            String lowerPkg = pkg.toLowerCase();
            if (lowerPkg.contains("controller")) {
                controllerLayer.add(pkg);
            } else if (lowerPkg.contains("service")) {
                serviceLayer.add(pkg);
            } else if (lowerPkg.contains("repository") || lowerPkg.contains("dao")) {
                repositoryLayer.add(pkg);
            } else if (lowerPkg.contains("entity") || lowerPkg.contains("domain") || lowerPkg.contains("model")) {
                domainLayer.add(pkg);
            } else if (lowerPkg.contains("config")) {
                configLayer.add(pkg);
            } else {
                otherLayers.add(pkg);
            }
        });

        if (!controllerLayer.isEmpty()) layers.put("控制层", controllerLayer);
        if (!serviceLayer.isEmpty()) layers.put("服务层", serviceLayer);
        if (!repositoryLayer.isEmpty()) layers.put("持久层", repositoryLayer);
        if (!domainLayer.isEmpty()) layers.put("领域层", domainLayer);
        if (!configLayer.isEmpty()) layers.put("配置层", configLayer);
        if (!otherLayers.isEmpty()) layers.put("其他", otherLayers);

        return layers;
    }

    private Map<String, List<String>> identifyModules(Map<String, List<CodeStructureEntity>> packageGroups) {
        Map<String, List<String>> modules = new HashMap<>();
        
        // 按包的第一层级分组
        packageGroups.keySet().forEach(pkg -> {
            String[] parts = pkg.split("\\.");
            if (parts.length >= 3) {
                String moduleName = parts[parts.length - 2]; // 倒数第二层作为模块名
                modules.computeIfAbsent(moduleName, k -> new ArrayList<>()).add(pkg);
            }
        });

        return modules;
    }

    private String identifyArchitectureStyle(Map<String, List<CodeStructureEntity>> packageGroups, String llmAnalysis) {
        // 基于包结构和LLM分析推断架构风格
        boolean hasControllerLayer = packageGroups.keySet().stream()
                .anyMatch(pkg -> pkg.toLowerCase().contains("controller"));
        boolean hasServiceLayer = packageGroups.keySet().stream()
                .anyMatch(pkg -> pkg.toLowerCase().contains("service"));
        boolean hasRepositoryLayer = packageGroups.keySet().stream()
                .anyMatch(pkg -> pkg.toLowerCase().contains("repository") || pkg.toLowerCase().contains("dao"));

        if (hasControllerLayer && hasServiceLayer && hasRepositoryLayer) {
            return "分层架构（Layered Architecture）";
        }

        if (llmAnalysis.contains("微服务") || llmAnalysis.contains("microservice")) {
            return "微服务架构（Microservices Architecture）";
        }

        if (llmAnalysis.contains("六边形") || llmAnalysis.contains("端口适配器")) {
            return "六边形架构（Hexagonal Architecture）";
        }

        return "混合架构";
    }

    private String buildDependencyGraph(List<CodeStructureEntity> structures) {
        StringBuilder graph = new StringBuilder();
        graph.append("依赖关系图：\n");
        
        // 简化的依赖关系
        Map<String, Set<String>> dependencies = new HashMap<>();
        
        for (CodeStructureEntity structure : structures.stream().limit(50).collect(Collectors.toList())) {
            String className = structure.getName();
            Set<String> deps = new HashSet<>();
            
            // 这里简化处理，实际应该解析imports
            if (structure.getDependencies() != null) {
                deps.add(structure.getDependencies());
            }
            
            if (!deps.isEmpty()) {
                dependencies.put(className, deps);
            }
        }

        dependencies.forEach((className, deps) -> {
            graph.append(className).append(" -> ").append(String.join(", ", deps)).append("\n");
        });

        return graph.toString();
    }

    private List<CodeStructureEntity> selectRepresentativeClasses(List<CodeStructureEntity> structures, int count) {
        // 选择不同类型的代表性类
        List<CodeStructureEntity> representatives = new ArrayList<>();
        
        // Controller
        representatives.addAll(structures.stream()
                .filter(s -> s.getName().endsWith("Controller"))
                .limit(2)
                .collect(Collectors.toList()));
        
        // Service
        representatives.addAll(structures.stream()
                .filter(s -> s.getName().endsWith("Service") && !s.getName().endsWith("ServiceImpl"))
                .limit(2)
                .collect(Collectors.toList()));
        
        // Repository
        representatives.addAll(structures.stream()
                .filter(s -> s.getName().endsWith("Repository") || s.getName().endsWith("Dao"))
                .limit(2)
                .collect(Collectors.toList()));
        
        // Entity
        representatives.addAll(structures.stream()
                .filter(s -> s.getStructureType().equals("class") && 
                        (s.getName().endsWith("Entity") || s.getName().endsWith("Model")))
                .limit(2)
                .collect(Collectors.toList()));
        
        // 如果不够，随机选择
        if (representatives.size() < count) {
            representatives.addAll(structures.stream()
                    .filter(s -> !representatives.contains(s))
                    .limit(count - representatives.size())
                    .collect(Collectors.toList()));
        }
        
        return representatives.stream().limit(count).collect(Collectors.toList());
    }

    private Map<String, Object> calculateCodeMetrics(String code, CodeStructureEntity structure) {
        Map<String, Object> metrics = new HashMap<>();
        
        metrics.put("lineCount", structure.getLineCount());
        metrics.put("methodCount", countMethods(code));
        metrics.put("dependencyCount", countDependencies(code));
        metrics.put("commentLines", countCommentLines(code));
        metrics.put("complexity", calculateComplexityScore(
                countMethods(code),
                structure.getLineCount() != null ? structure.getLineCount() : 0,
                countDependencies(code)
        ));
        
        return metrics;
    }

    private int countMethods(String code) {
        // 简单统计方法数量（匹配 public/private/protected 方法）
        int count = 0;
        String[] lines = code.split("\n");
        for (String line : lines) {
            String trimmed = line.trim();
            if (trimmed.matches("^(public|private|protected)\\s+.*\\(.*\\)\\s*\\{?$")) {
                count++;
            }
        }
        return count;
    }

    private int countDependencies(String code) {
        // 统计import语句
        return (int) Arrays.stream(code.split("\n"))
                .filter(line -> line.trim().startsWith("import "))
                .count();
    }

    private int countCommentLines(String code) {
        return (int) Arrays.stream(code.split("\n"))
                .filter(line -> {
                    String trimmed = line.trim();
                    return trimmed.startsWith("//") || trimmed.startsWith("/*") || 
                           trimmed.startsWith("*") || trimmed.endsWith("*/");
                })
                .count();
    }

    private int calculateComplexityScore(int methodCount, int lineCount, int dependencyCount) {
        return (int) (methodCount * 0.3 + lineCount * 0.01 + dependencyCount * 0.5);
    }

    private List<String> quickSecurityScan(String code) {
        List<String> issues = new ArrayList<>();
        
        if (code.contains("password") && code.contains("System.out") || code.contains("log.info")) {
            issues.add("可能在日志中打印密码");
        }
        
        if (code.contains("SELECT") && code.contains("+")) {
            issues.add("可能存在SQL注入风险");
        }
        
        if (code.contains("HttpServletRequest") && !code.contains("validate")) {
            issues.add("输入验证可能不足");
        }
        
        if (code.contains("@RequestMapping") && !code.contains("@PreAuthorize") && 
            !code.contains("@Secured")) {
            issues.add("可能缺少权限控制");
        }
        
        return issues;
    }

    private List<String> quickPerformanceScan(String code) {
        List<String> issues = new ArrayList<>();
        
        if (code.contains("for") && code.contains("for") && 
            code.lastIndexOf("for") - code.indexOf("for") < 500) {
            issues.add("可能存在嵌套循环");
        }
        
        if (code.contains("findAll()") || code.contains("list()")) {
            issues.add("可能一次性加载大量数据");
        }
        
        if (code.contains("Thread.sleep")) {
            issues.add("使用Thread.sleep可能影响性能");
        }
        
        if (code.contains("new ") && code.contains("for")) {
            issues.add("在循环中创建对象");
        }
        
        return issues;
    }

    private List<String> findDeprecatedUsages(String code) {
        List<String> deprecated = new ArrayList<>();
        
        String[] lines = code.split("\n");
        for (int i = 0; i < lines.length; i++) {
            if (lines[i].contains("@Deprecated")) {
                // 找到下一个方法或类
                if (i + 1 < lines.length) {
                    deprecated.add(lines[i + 1].trim());
                }
            }
        }
        
        return deprecated;
    }

    private String extractClassNamePattern(String className) {
        // 提取类名模式（如 UserServiceImpl -> Service）
        if (className.endsWith("Impl")) return "Impl";
        if (className.endsWith("Controller")) return "Controller";
        if (className.endsWith("Service")) return "Service";
        if (className.endsWith("Repository")) return "Repository";
        if (className.endsWith("Entity")) return "Entity";
        return "Other";
    }

    private int calculateTechnicalDebtScore(List<Map<String, Object>> debtItems) {
        // 计算技术债务分数（0-100，越高越好）
        int score = 100;
        
        for (Map<String, Object> item : debtItems) {
            String severity = (String) item.get("severity");
            if ("高".equals(severity)) {
                score -= 10;
            } else if ("中".equals(severity)) {
                score -= 5;
            } else {
                score -= 2;
            }
        }
        
        return Math.max(0, score);
    }

    private String getDebtLevel(int score) {
        if (score >= 80) return "优秀";
        if (score >= 60) return "良好";
        if (score >= 40) return "一般";
        if (score >= 20) return "较差";
        return "严重";
    }

    private List<String> findLongMethods(String code) {
        List<String> longMethods = new ArrayList<>();
        
        String[] lines = code.split("\n");
        String currentMethod = null;
        int methodStartLine = 0;
        int braceCount = 0;
        
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i].trim();
            
            // 检测方法开始
            if (line.matches("^(public|private|protected)\\s+.*\\(.*\\).*$")) {
                currentMethod = line;
                methodStartLine = i;
                braceCount = 0;
            }
            
            // 统计大括号
            braceCount += line.chars().filter(ch -> ch == '{').count();
            braceCount -= line.chars().filter(ch -> ch == '}').count();
            
            // 方法结束
            if (currentMethod != null && braceCount == 0 && i > methodStartLine) {
                int methodLength = i - methodStartLine;
                if (methodLength > 50) {
                    longMethods.add(currentMethod + " (" + methodLength + " 行)");
                }
                currentMethod = null;
            }
        }
        
        return longMethods;
    }

    private List<String> identifyGoodPractices(String code, CodeStructureEntity structure) {
        List<String> practices = new ArrayList<>();
        
        if (code.contains("@Transactional")) {
            practices.add("使用声明式事务管理");
        }
        
        if (code.contains("@Slf4j") || code.contains("Logger")) {
            practices.add("使用日志框架进行日志记录");
        }
        
        if (code.contains("@Valid") || code.contains("@Validated")) {
            practices.add("使用参数校验");
        }
        
        if (code.contains("Optional")) {
            practices.add("使用Optional处理空值");
        }
        
        if (code.contains("try-with-resources") || code.matches(".*try\\s*\\(.*\\).*")) {
            practices.add("使用try-with-resources自动资源管理");
        }
        
        if (structure.getLineCount() != null && structure.getLineCount() < 200) {
            practices.add("类的大小适中，职责单一");
        }
        
        return practices;
    }

    private String buildDesignPrinciplesSummaryPrompt(List<Map<String, Object>> classAnalyses) {
        StringBuilder prompt = new StringBuilder();
        prompt.append("基于以下代码质量分析结果，请生成一份整体的设计原则遵循度评估报告：\n\n");
        
        for (Map<String, Object> analysis : classAnalyses) {
            prompt.append("## ").append(analysis.get("className")).append("\n");
            prompt.append(truncate(analysis.get("qualityAnalysis").toString(), 300)).append("\n\n");
        }
        
        prompt.append("\n请总结：\n");
        prompt.append("1. 整体设计质量评估\n");
        prompt.append("2. SOLID原则的遵循情况\n");
        prompt.append("3. 主要优点\n");
        prompt.append("4. 主要问题\n");
        prompt.append("5. 改进建议\n");
        
        return prompt.toString();
    }

    private String buildComplexityAnalysisPrompt(String className, String code, Map<String, Object> metrics) {
        return String.format("""
                请深度分析以下复杂类的代码：
                
                **类名**: %s
                **指标**: 方法数=%s, 行数=%s, 依赖数=%s, 复杂度分数=%s
                
                ```java
                %s
                ```
                
                请分析：
                1. 为什么这个类如此复杂？
                2. 复杂性的主要来源是什么？
                3. 如何降低复杂度？提供3-5个具体的重构建议
                4. 重构的优先级和预期收益
                
                请详细分析（800-1000字）。
                """,
                className,
                metrics.get("methodCount"),
                metrics.get("lineCount"),
                metrics.get("dependencyCount"),
                metrics.get("complexityScore"),
                truncate(code, 5000)
        );
    }

    private String truncate(String text, int maxLength) {
        if (text == null) return "";
        if (text.length() <= maxLength) return text;
        return text.substring(0, maxLength) + "...[已截断]";
    }

    // ========== 优化的上下文传递方法 ==========

    /**
     * 构建上下文摘要（从深度阅读和之前的分析结果）
     */
    private String buildContextSummary(Map<String, Object> deepReadingReport, Map<String, Object> previousAnalysis) {
        StringBuilder summary = new StringBuilder();
        
        summary.append("# 基于深度理解的上下文\n\n");
        
        try {
            // 从深度阅读中提取关键信息
            if (deepReadingReport != null) {
                // 综合理解
                String comprehensiveUnderstanding = (String) deepReadingReport.get("comprehensiveUnderstanding");
                if (comprehensiveUnderstanding != null && !comprehensiveUnderstanding.isEmpty()) {
                    summary.append("## 项目综合理解\n");
                    summary.append(truncate(comprehensiveUnderstanding, 800)).append("\n\n");
                }
                
                // 关键问题回答
                @SuppressWarnings("unchecked")
                Map<String, String> keyAnswers = (Map<String, String>) deepReadingReport.get("keyQuestionsAnswers");
                if (keyAnswers != null && !keyAnswers.isEmpty()) {
                    summary.append("## 关键问题解答\n");
                    keyAnswers.forEach((question, answer) -> {
                        summary.append("**Q**: ").append(truncate(question, 100)).append("\n");
                        summary.append("**A**: ").append(truncate(answer, 200)).append("\n\n");
                    });
                }
            }
            
            // 从之前的分析中提取关键信息
            if (previousAnalysis != null) {
                // 项目概览
                @SuppressWarnings("unchecked")
                Map<String, Object> overview = (Map<String, Object>) previousAnalysis.get("overview");
                if (overview != null && overview.containsKey("llmSummary")) {
                    summary.append("## 项目概览\n");
                    summary.append(truncate(overview.get("llmSummary").toString(), 500)).append("\n\n");
                }
                
                // 技术栈
                @SuppressWarnings("unchecked")
                Map<String, Object> techStack = (Map<String, Object>) previousAnalysis.get("techStack");
                if (techStack != null && techStack.containsKey("frameworks")) {
                    summary.append("## 技术栈\n");
                    @SuppressWarnings("unchecked")
                    List<String> frameworks = (List<String>) techStack.get("frameworks");
                    summary.append("使用的主要框架: ").append(String.join(", ", frameworks)).append("\n\n");
                }
            }
            
        } catch (Exception e) {
            log.warn("构建上下文摘要时出错", e);
        }
        
        return summary.toString();
    }

    /**
     * 构建带上下文的架构分析提示词
     */
    private String buildArchitecturePromptWithContext(Map<String, Object> structureSummary, 
                                                       String dependencies, 
                                                       String context) {
        return String.format("""
                基于对项目代码的深度理解：
                
                %s
                
                ---
                
                现在请进行更深入的架构分析：
                
                ## 项目结构
                %s
                
                ## 依赖关系
                %s
                
                ---
                
                请结合你对整个项目的深度理解，进行**多层次的架构分析**：
                
                ## 一、架构风格识别 (20%%)
                1. **整体架构风格**:
                   - 这是什么类型的架构？（分层/六边形/微服务/事件驱动等）
                   - 结合你对代码的理解，为什么判断是这种架构？
                
                2. **架构演化**:
                   - 从代码结构能看出架构是如何演化的吗？
                
                ## 二、分层与模块化分析 (30%%)
                3. **分层设计**:
                   - 系统如何分层？每层的职责是什么？
                   - 层与层之间的依赖关系如何？
                
                4. **模块划分**:
                   - 模块如何划分？划分的合理性如何？
                   - 模块之间的耦合度如何？内聚性如何？
                
                ## 三、核心组件分析 (20%%)
                5. **关键组件识别**:
                   - 结合你对代码的理解，哪些是核心组件？
                   - 这些组件如何协作？
                
                ## 四、设计质量评估 (20%%)
                6. **架构优点**: 这个架构设计有哪些亮点？
                7. **潜在问题**: 存在哪些架构层面的问题？
                8. **改进建议**: 如何改进架构设计？
                
                ## 五、架构决策分析 (10%%)
                9. **关键决策**: 识别出的关键架构决策有哪些？为什么这样设计？
                
                请详细分析（1500-2000字），要结合你对代码的深度理解。
                """,
                truncate(context, 2000),
                formatMap(structureSummary),
                truncate(dependencies, 1500)
        );
    }

    /**
     * 格式化 Map 为字符串
     */
    private String formatMap(Map<String, Object> map) {
        if (map == null || map.isEmpty()) return "无";
        StringBuilder sb = new StringBuilder();
        map.forEach((key, value) -> {
            sb.append("- ").append(key).append(": ").append(value).append("\n");
        });
        return sb.toString();
    }
}

